<!-- 
	登录页
	1. 已经登录的用户应该是进不来这页面的。
	https://www.html5plus.org/doc/zh_cn/oauth.html
	
	state
		normal 普通账号密码登录
		qq QQ登录
		
	state=qq时
		user.qq.state
			0 初始，加载中
			1 没有找到，选择绑定还是注册
			2 绑定
			3 注册
	
	有几种状态
	0输入框
	1qq登录好了
 -->
<script setup lang="ts">
	import { reactive } from 'vue'
	import OAuth, { type AuthServiceId } from '@/utils/oAuth'
	import type { User } from '@/env'
	import * as API from '@/api/user'
	import { login } from '@/stores/global'
	import { baseURL } from '@/stores/constant'

	/** 页面状态 */
	const state = ref('normal')

	// 表单数据
	const form = reactive({
		name: '',
		pswd: '',
		captcha: ''
	})

	// 用户数据
	const user = reactive<{
		[platform in AuthServiceId]?: { state : number, unionid : string, data : any, [key : string] : any }
	}>({
		qq: {
			state: 0,
			unionid: '',
			/** 是否使用QQ头像 */
			useImg: true,
			data: {},
		}
	})

	// 用户名密码登录
	const doLogin = async () => {
		let user : User = await API.login(form)
		if (user) login(user.token!)
		else plus.nativeUI.alert('用户名或密码错误');
	}

	const qqLogin = async () => {
		state.value = 'qq'
		const { target: data } = await OAuth.login('qq')
		user.qq!.data = data // 数据拷贝
		user.qq!.unionid = data.userInfo.unionid
		// 先看有没有这个用户
		const count = await API.haveUser({ unionidQq: user.qq!.unionid })

		if (count === 0) {
			// 没找到用户，注册或绑定
			user.qq!.state = 1
		} else { // 找到用户，直接登录
			const resUser = await API.login({ unionidQq: user.qq!.unionid })
			if (resUser) login(resUser.token!)
		}
	}

	// 绑定
	const bind = async () => {
		// 先登录获取token，再token和openid一起绑定
		const resUser = await API.login(form)
		if (resUser) {
			// 先绑定平台，再更新头像
			await API.bindPlatform({ token: resUser.token, platform: 'qq', unionid: user.qq!.unionid })
			if (user.qq!.useImg) {
				const userJson = { img: user.qq!.data?.userInfo?.figureurl_qq }
				await API.updateUser({ token: resUser.token, userJson: JSON.stringify(userJson) })
			}
			login(resUser.token!)
		} else {
			return uni.showToast({ title: '用户名或密码错误', icon: 'error' });
		}
	}

	//**** 注册新用户
	const captchaImg = ref('')
	const changeImg = () => {
		captchaImg.value = baseURL + '/user/signin/captcha_img?' + Math.random()
	}
	// 2.用户选择注册新用户
	// 获取QQ名作为默认名字，叫他设置用户名（万一被占用了）和密码
	const handleNew = () => {
		user.qq!.state = 3
		form.name = user.qq!.data?.userInfo?.nickname
		nextTick(changeImg)
		API.haveUser({ name: form.name }).then(count => {
			if (count) uni.showToast({ title: '该用户名被占用了哦', icon: 'error' })
		})
	}
	const pswd2 = ref('')
	const sign = async () => {
		// 普通校验
		if (form.pswd.trim() != pswd2.value.trim())
			return uni.showToast({ title: '两次密码不一致', icon: 'error' })
		// 先注册
		const userid = await API.signin(form)
		if (userid === 0) return uni.showToast({ title: '用户名已存在', icon: 'error' })
		if (userid === -1) return uni.showToast({ title: '验证码错误', icon: 'error' })
		// 再登录获取token
		const resUser = await API.login({ name: form.name, pswd: form.pswd })
		console.log('🐤绑定')
		if (resUser.token) {
			// 先绑定平台
			await API.bindPlatform({ token: resUser.token, platform: 'qq', unionid: user.qq!.unionid })
			// 再换头像
			const userJson = { img: user.qq!.data?.userInfo?.figureurl_qq }
			await API.updateUser({ token: resUser.token, userJson: JSON.stringify(userJson) })
			login(resUser.token!)
		}
	}
</script>


<template>
	<view class="login-page" @touchmove.stop.prevent="() => {}">
		<!-- 没有登录的用户 -->
		<view v-if="state==='normal'" class='normal'>
			<view class="banner">
				欢迎来到多元记
				把你写成书
			</view>
			<view class="main">
				<view class="form">
					<u--input placeholder="用户名" border="surround" v-model="form.name" />
					<u--input placeholder="密码" border="surround" v-model="form.pswd" type="password" />
				</view>
				<u-button @click='doLogin' type="primary" text="登录" />
			</view>
			<view class="three">
				<view>
					<image src="https://s1.hdslb.com/bfs/static/jinkela/passport-pc/assets/wechat.png" alt="微信登录" />
				</view>
				<view>
					<image @click="qqLogin" src="https://s1.hdslb.com/bfs/static/jinkela/passport-pc/assets/qq.png" alt="QQ登录" />
				</view>
			</view>
		</view>
		<!-- QQ登录模式 -->
		<view v-else-if="state==='qq'" class="qq">
			<view class="banner">
				<view class="title">QQ登录</view>
				<view class="user">{{user.qq.data?.userInfo?.nickname}}</view>
				<image :src="user.qq.data?.userInfo?.figureurl_qq" />
			</view>

			<view class="main">
				<view v-if="user.qq.state === 0" class="top"><u-loadmore status='loading' /></view>
				<template v-if="user.qq.state === 1">
					<view class="top">没有找到这个QQ对应的Logger</view>
					<view class="bottom">
						<u-button @click='user.qq.state = 2' type="primary" text="绑定已有账号" />
						<u-button @click='handleNew' type="primary" text="注册新用户" />
					</view>

				</template>
				<template v-if="user.qq.state === 2">
					<view class="top">绑定已有账号</view>
					<view class="bottom">
						<u--input placeholder="用户名" border="surround" v-model="form.name" />
						<u--input placeholder="密码" border="surround" v-model="form.pswd" type="password" />
						<view style="display: flex;justify-content: space-between;">使用QQ头像<u-switch v-model="user.qq.useImg" />
						</view>
						<u-button @click='bind' type="primary" text="绑定并登录" />
					</view>
				</template>
				<template v-if="user.qq.state === 3">
					<view class="top">注册新用户</view>
					<view class="bottom">
						<u--input border="surround" placeholder="用户名" v-model="form.name" />
						<u--input border="surround" placeholder="密码" v-model="form.pswd" type="password" />
						<u--input border="surround" placeholder="确认密码" v-model="pswd2" type="password" />
						<view class="captcha">
							<u--input border="surround" placeholder="验证码" v-model="form.captcha" />
							<image :src='captchaImg' alt="验证码看不清，换一张" @click="changeImg" />
						</view>
					</view>

					<u-button @click='sign' type="primary" text="注册并登录" />
				</template>
			</view>
		</view>
		<!-- 其他登录方式 -->

	</view>
</template>

<style lang="scss" scoped>
	.login-page {
		height: 100vh;
		width: 100vw;

		// nomal
		.normal {
			height: 100%;
			width: 100%;
			display: flex;
			flex-direction: column;
			padding: 0 32rpx;


			.banner {
				margin-top: var(--status-bar-height);
			}

			>.main {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: center;
				gap: 32rpx;

				.form {
					display: flex;
					flex-direction: column;

					gap: 32rpx;
				}
			}

			.three {
				display: flex;
				justify-content: center;
				// align-items: center;
				gap: 48rpx;
				margin-bottom: 32rpx;

				>view {
					width: 80rpx;
					height: 80rpx;

					>image {
						width: 100%;
						height: 100%;
					}
				}
			}
		}

		.qq {
			height: 100%;
			width: 100%;
			display: flex;
			flex-direction: column;
			padding: 0 32rpx;


			.banner {
				margin-top: var(--status-bar-height);
				display: flex;
				align-items: center;
				gap: 20rpx;


				.title {
					flex: 1;
				}

				.user {}

				image {
					width: 70rpx;
					height: 70rpx;
					border-radius: 50%;
				}
			}

			>.main {
				flex: 1;
				display: flex;
				flex-direction: column;
				gap: 30rpx;

				padding: 40rpx 0;

				>.top {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: center;
				}

				.bottom {
					display: flex;
					flex-direction: column;

					gap: 32rpx;

					.captcha {
						display: flex;
						// align-items: center;
						gap: 16rpx;
						border: 1px solid red;

						input {
							// flex: 1;
							// width: 0;
							width: 50%;
						}

						image {
							height: 100%;
							border: 1px solid red;
						}
					}
				}

				.form {
					display: flex;
					flex-direction: column;

					gap: 30rpx;
				}
			}
		}



	}
</style>